﻿using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;

namespace CMS.Controls
{
    public class FormPanel : FormBase
    {
        public delegate bool ValidateHandler(Control control);

        public static ValidateHandler TextNoEmptyValidator =
            control =>
            !string.IsNullOrWhiteSpace(control.Text);

        /// <summary>
        /// 表明是否在读取状态,如果不在只读状态,则会自动触发表单验证
        /// </summary>
        public bool ReadOnly { get; set; } = false;


        public FormPanel()
        {
            SuspendLayout();
            LayoutD = new LayoutDetial()
            {
                Columns = new ColumnDefinition[]
                {
                    new ColumnDefinition()
                    {
                        Alignment=HorizontalAlignment.Right,
                        Fill=true,
                        Padding=new Padding(3),
                        Width=100
                    },
                    new ColumnDefinition()
                    {
                        Alignment=HorizontalAlignment.Center,
                        Fill=true,
                        Padding=new Padding(3),
                        Width=150
                    },
                    new ColumnDefinition()
                    {
                        Alignment=HorizontalAlignment.Left,
                        Fill=false,
                        Padding=new Padding(3),
                        Width=30
                    }
                },
                RowHeight = 50
            };
            ResumeLayout();
        }

        public FormPanel(int itemHeight, int itemWidth1, int itemWidth2, int itemWidth3)
        {
            Width = itemWidth1 + itemWidth2 + itemWidth3;
            LayoutD = new LayoutDetial()
            {
                Columns = new ColumnDefinition[]
                {
                    new ColumnDefinition()
                    {
                        Alignment=HorizontalAlignment.Right,
                        Fill=true,
                        Padding=new Padding(3),
                        Width=itemWidth1
                    },
                    new ColumnDefinition()
                    {
                        Alignment=HorizontalAlignment.Center,
                        Fill=true,
                        Padding=new Padding(3),
                        Width=itemWidth2
                    },
                    new ColumnDefinition()
                    {
                        Alignment=HorizontalAlignment.Left,
                        Fill=false,
                        Padding=new Padding(3),
                        Width=itemWidth3
                    }
                },
                RowHeight = itemHeight
            };
        }

        /// <summary>
        /// 更新验证
        /// </summary>
        /// <param name="control"></param>
        /// <param name="validateDisplay"></param>
        /// <param name="handler"></param>
        /// <returns></returns>
        private bool _UpdateValidate(Control control, PictureBox validateDisplay, ValidateHandler handler)
        {
            if (handler.Invoke(control))
            {
                validateDisplay.Image = Resource1.Right16;
                return true;
            }
            else
            {
                validateDisplay.Image = Resource1.Wrong16;
                return false;
            }
        }

        /// <summary>
        /// 添加可填写字段的表单信息
        /// </summary>
        /// <param name="name"></param>
        /// <param name="control"></param>
        /// <param name="handler"></param>
        public void AddField(string name, Control control, ValidateHandler handler = null, ColumnDefinition[] definition = null)
        {
            PictureBox PB_Validate = new PictureBox() { Size = new Size(16, 16) };
            Label L_Name = new Label() { Text = name, AutoSize = true };

            if (handler != null)
            {
                control.Validating += (sender, e) =>
                {
                    _UpdateValidate(control, PB_Validate, handler);
                };
            }
            AddRow(new RowDetial()
            {
                Controls = new Control[]
                {
                    L_Name,control,PB_Validate
                },
                Tag = handler,
                ColumnDefinitions = definition
            });
        }

        /// <summary>
        /// 添加路径之类的信息条,button需要手动与建立联系此容器只是起到布局的作用
        /// </summary>
        /// <param name="name"></param>
        /// <param name="control"></param>
        /// <param name="button"></param>
        public void AddPathField(string name, Control control, FolderBrowserDialog dialog)
        {
            Label L_Name = new Label() { Text = name, AutoSize = true };
            Button Bn_Open = new MyButton() { Text = "浏览", Size = new Size(40, 20) };
            Bn_Open.Click += (sender, e) =>
            {
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    control.Text = dialog.SelectedPath;
                }
            };
            AddRow(new RowDetial()
            {
                Controls = new Control[]
                {
                    L_Name,control,Bn_Open
                }
            });
        }

        /// <summary>
        /// 获取一个基于整体布局的列定义副本
        /// </summary>
        /// <returns></returns>
        public ColumnDefinition[] CloneColumnDefinition(params bool[] overrides)
        {
            ColumnDefinition[] ret = (ColumnDefinition[])LayoutD.Columns.Clone();
            for (int i = 0; i < ret.Length; i++)
            {
                if (i < overrides.Length && overrides[i])
                {
                    ret[i] = (ColumnDefinition)ret[i].Clone();
                }
                else
                {
                    ret[i] = null;
                }
            }
            return ret;
        }

        protected override void OnValidating(CancelEventArgs e)
        {
            base.OnValidating(e);
            foreach (RowDetial row in Rows)
            {
                if (row.Tag != null)
                {
                    _UpdateValidate(row.Controls[1], row.Controls[2] as PictureBox, row.Tag as ValidateHandler);
                }
            }
        }

        /// <summary>
        /// 清除所有验证
        /// </summary>
        public void ClearValidate()
        {
            foreach (RowDetial row in Rows)
            {
                if (row.Tag != null)
                {
                    if (row.Controls[2] is PictureBox pb)
                    {
                        pb.Image = null;
                    }
                }
            }
        }

        /// <summary>
        /// 清除表单中的内容
        /// </summary>
        public void ClearContent()
        {
            foreach (RowDetial row in Rows)
            {
                if (row.Controls[1] is ComboBox combo)
                {
                    combo.SelectedIndex = -1;
                }
                else if (row.Controls[1] is TextBox textBox)
                {
                    textBox.Text = "";
                }
                else if (row.Controls[1] is MyNumericUpDown num)
                {
                    num.Value = 0;
                }
            }
        }

        /// <summary>
        /// 验证表单是否合法
        /// </summary>
        /// <returns></returns>
        public bool Validate()
        {
            bool success = true;
            foreach (RowDetial row in Rows)
            {
                if (row.Tag != null)
                {
                    success &= _UpdateValidate(row.Controls[1], row.Controls[2] as PictureBox, row.Tag as ValidateHandler);
                }
            }
            return success;
        }
    }
}
